﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Document;
using YJTTool.Configure.ViewModels;

namespace YJTTool.Configure.Views
{
    /// <summary>
    /// JsonConversionView.xaml 的交互逻辑
    /// </summary>
    public partial class JsonConversionView : UserControl
    {
        public JsonConversionView()
        {
            InitializeComponent();
        }


        private void InputEditor_TextChanged(object sender, EventArgs e)
        {
            if (DataContext is JsonConversionViewModel vm)
            {
                vm.EditorLineCount = InputEditor.LineCount;
            }
        }

        private void TextArea_TextEntering(object sender, TextCompositionEventArgs e)
        {
            if (e.Text == "\n")
            {
                HandleSmartIndent(sender, e);
            }
        }

        private void HandleSmartIndent(object sender, TextCompositionEventArgs e)
        {
            var editor = (TextEditor)sender;
            var document = editor.Document;
            var caretOffset = editor.CaretOffset;
            var currentLine = document.GetLineByOffset(caretOffset);

            // 获取当前行的缩进
            var indent = GetIndentation(document, currentLine);

            // 插入新行和缩进
            document.Insert(caretOffset, "\n" + indent);

            // 移动光标到新位置
            editor.CaretOffset = caretOffset + indent.Length + 1;
            e.Handled = true;
        }

        private string GetIndentation(TextDocument document, DocumentLine line)
        {
            var lineText = document.GetText(line.Offset, line.Length);
            return new string(lineText.TakeWhile(c => c == ' ' || c == '\t').ToArray());
        }
    }
}
